package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;

import util.CodeBuilder;
import util.CodeBuilder.BuildType;
import util.DataSourceInfoUtil;
import util.PropertiesUtil;
import util.Utils;

public class View extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5725706474912002588L;
	private static HashMap<String,String> configHash=new LinkedHashMap<String,String>(8);
	private static String readMe="";
	private JPanel contentPanel=null;
	private JPanel jPanelContent=null;
	private JPanel configJpanel=null;
	private JPanel readMeJpanel=null;


	static {
		initView();
	}
	/**
	 * Launch the application.
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					View frame = new View();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	private static void initView() {
		initConfigInfo();		
		initReadMeInfo();
	}

	/**
	 * Create the frame.
	 */
	public View() {
		setTitle("管理平台代码生成器");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(500, 100, 800, 664);
		contentPanel=new JPanel();
		contentPanel.setLayout(new BorderLayout());
		setContentPane(contentPanel);
		
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		JMenu menuMain = new JMenu("首页");
		menuBar.add(menuMain);
		
		JMenu menu = new JMenu("配置参数");
		menuBar.add(menu);
		
		JMenu menu_1 = new JMenu("关于");
		menuBar.add(menu_1);
		
		
		
		initMainContentPanel();
		
		initConfigPanel();
		
		initReadMePanel();

		menu.addMenuListener(new MenuListener() {
			
			@Override
			public void menuSelected(MenuEvent e) {
				switchPanel(configJpanel);
			}
			@Override
			public void menuDeselected(MenuEvent e) {
			}
			@Override
			public void menuCanceled(MenuEvent e) {
//				switchPanel(jPanelContent);
			}
		});
		
		menu_1.addMenuListener(new MenuListener() {
			
			@Override
			public void menuSelected(MenuEvent e) {
				switchPanel(readMeJpanel);
			}
			@Override
			public void menuDeselected(MenuEvent e) {
			}
			@Override
			public void menuCanceled(MenuEvent e) {
			}
		});
		
		menuMain.addMenuListener(new MenuListener() {
			
			@Override
			public void menuSelected(MenuEvent e) {
				switchPanel(jPanelContent);
			}
			@Override
			public void menuDeselected(MenuEvent e) {
			}
			@Override
			public void menuCanceled(MenuEvent e) {
			}
		});
	}
	
	private void initReadMePanel() {
		JPanel readMePanel = new JPanel();
		readMePanel.setBorder(new EmptyBorder(5, 5, 5, 5));

		JTextPane jtp=new JTextPane();
		jtp.setEditable(false);
		jtp.setText(readMe);
		jtp.setBounds(0, 0, 595, 405);
		readMePanel.add(jtp);
		readMeJpanel=readMePanel;
		readMePanel.setLayout(null);

	}

	//切换面板
	private void switchPanel(JPanel jp) {
		BorderLayout b=(BorderLayout) contentPanel.getLayout();
		Component compent=b.getLayoutComponent(BorderLayout.CENTER);
		contentPanel.remove(compent);// 删除内容面板中间原来的组建
		contentPanel.add(jp, BorderLayout.CENTER);// 添加要切换的面板
		contentPanel.validate();// 重构内容面板
		contentPanel.repaint();// 重绘内容面板
	}
	
	private void initMainContentPanel() {
		JPanel contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		
		JLabel label = new JLabel("请选择需要生成的表:");
		label.setBounds(121, 91, 129, 15);
		label.setVisible(false);
		contentPane.add(label);
		DataSourceInfoUtil.URL=configHash.get("DataSourceUrl");
		DataSourceInfoUtil.USERNAME=configHash.get("UserName");
		DataSourceInfoUtil.PASSWORD=configHash.get("Password");
		List<String> tables=DataSourceInfoUtil.getTables();
		List<String> value=new ArrayList<String>();
		value.add("全选");
		value.addAll(tables);
        MultiComboBox mulit = new MultiComboBox(value.toArray(),new Object[]{"全选"});
        mulit.setBackground(Color.LIGHT_GRAY);
        mulit.setVisible(false);
		mulit.setBounds(255, 91, 299, 60);
		contentPane.add(mulit);
		
		JCheckBox chckbxNewCheckBox = new JCheckBox("不是全库生成");
		chckbxNewCheckBox.setBounds(121, 45, 103, 23);
		contentPane.add(chckbxNewCheckBox);
		chckbxNewCheckBox.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(label.isVisible()) {
					label.setVisible(false);
				}else {
				    label.setVisible(true);
				}
				if(mulit.isVisible()) {
					mulit.setVisible(false);
				}else {
					mulit.setVisible(true);
				}
			}
		});
		
		
		JLabel lblNewLabel_3 = new JLabel("主表名称:");
		lblNewLabel_3.setBounds(121, 171, 93, 15);
		contentPane.add(lblNewLabel_3);
		
		JTextField txtTab = new JTextField();
		txtTab.setToolTipText("");
		txtTab.setBounds(194, 168, 154, 21);
		contentPane.add(txtTab);
		txtTab.setColumns(10);
		
		JLabel label_1 = new JLabel("可空");
		label_1.setBounds(355, 171, 54, 15);
		contentPane.add(label_1);
		
		JButton button = new JButton("生成");
		button.setBounds(255, 512, 93, 23);
		contentPane.add(button);
		button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				//校验配置文件是否配置好了
				if(!checkConfig(configHash)) {
					outInfoMessage(false,"请配置参数！");
					return;
				}
				
				DataSourceInfoUtil.URL=configHash.get("DataSourceUrl");
				DataSourceInfoUtil.USERNAME=configHash.get("UserName");
				DataSourceInfoUtil.PASSWORD=configHash.get("Password");
				CodeBuilder.config=configHash;
				
				CodeBuilder cb=new CodeBuilder();
				try {
					String mainTable=lblNewLabel_3.getText();
					List<String> selectedTable=Arrays.stream(mulit.getSelectedValues()).map(s->(String)s).collect(Collectors.toList());
					if(chckbxNewCheckBox.isSelected()&&!Utils.isEmpty(mainTable)) {
						outInfoMessage(cb.build(selectedTable,BuildType.MAINTABLE,mainTable),null);
					}else if(chckbxNewCheckBox.isSelected()&&Utils.isEmpty(mainTable)) {
						outInfoMessage(cb.build(selectedTable,BuildType.NOMAINTABLE,null),null);
					}else {
						outInfoMessage(cb.buildAll(),null);
					}
					return;
				}catch (Exception ex) {
					JOptionPane.showMessageDialog(configJpanel, "失败!"+ex.getMessage(), "提示",JOptionPane.WARNING_MESSAGE);  
                    return;
				}

			}
		});
		
		jPanelContent=contentPane;
		contentPane.setLayout(null);
		
		contentPanel.add(contentPane, BorderLayout.CENTER);//中间面板
		
		JCheckBox chckbxNewCheckBox_1 = new JCheckBox("没有操作区域(增,删,改)");
		chckbxNewCheckBox_1.setBounds(121, 210, 207, 23);
		contentPane.add(chckbxNewCheckBox_1);
		chckbxNewCheckBox_1.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(configHash.containsKey("NoOperatingArea")&&"true".equals(configHash.get("NoOperatingArea")))
					configHash.remove("NoOperatingArea");
					configHash.put("NoOperatingArea","true");
			}
		});
		JCheckBox chckbxNewCheckBox_2 = new JCheckBox("需要兼外语");
		chckbxNewCheckBox_2.setBounds(330, 210, 103, 23);
		contentPane.add(chckbxNewCheckBox_2);
		chckbxNewCheckBox_2.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(configHash.containsKey("ForeignLanguageRequired")&&"true".equals(configHash.get("ForeignLanguageRequired")))
					configHash.remove("ForeignLanguageRequired");
					configHash.put("ForeignLanguageRequired","true");
			}
		});
		
		JLabel lblNewLabel_5 = new JLabel("哪些字段不需要显示在jsp中(以逗号分隔):");
		lblNewLabel_5.setBounds(121, 245, 240, 15);
		contentPane.add(lblNewLabel_5);
		
		JLabel lblNewLabel_6 = new JLabel("哪些字段作为检索条件(以逗号分隔):");
		lblNewLabel_6.setBounds(121, 324, 229, 15);
		contentPane.add(lblNewLabel_6);
		
		JTextArea textArea = new JTextArea();
		textArea.setRows(2);
		textArea.setColumns(15);
		textArea.setBounds(121, 270, 433, 44);
		contentPane.add(textArea);
		
		JTextArea textArea_1 = new JTextArea();
		textArea_1.setRows(2);
		textArea_1.setColumns(15);
		textArea_1.setBounds(121, 343, 433, 44);
		contentPane.add(textArea_1);
		
		JCheckBox chckbxNewCheckBox_3 = new JCheckBox("只生成jsp代码");
		chckbxNewCheckBox_3.setBounds(121, 434, 129, 23);
		contentPane.add(chckbxNewCheckBox_3);
		chckbxNewCheckBox_3.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(configHash.containsKey("OnlyJspFile")&&"true".equals(configHash.get("OnlyJspFile")))
				configHash.remove("OnlyJspFile");
				configHash.put("OnlyJspFile","true");
			}
		});
		
		JCheckBox chckbxNewCheckBox_4 = new JCheckBox("只生成handler代码");
		chckbxNewCheckBox_4.setBounds(255, 434, 145, 23);
		contentPane.add(chckbxNewCheckBox_4);
		chckbxNewCheckBox_4.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(configHash.containsKey("OnlyHandlerFile")&&"true".equals(configHash.get("OnlyHandlerFile")))
				configHash.remove("OnlyHandlerFile");
				configHash.put("OnlyHandlerFile","true");
			}
		});
		
		JCheckBox chckbxNewCheckBox_5 = new JCheckBox("只生成Core代码");
		chckbxNewCheckBox_5.setBounds(402, 434, 152, 23);
		contentPane.add(chckbxNewCheckBox_5);
		chckbxNewCheckBox_5.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(configHash.containsKey("OnlyCoreFile")&&"true".equals(configHash.get("OnlyCoreFile")))
				configHash.remove("OnlyCoreFile");
				configHash.put("OnlyCoreFile","true");
			}
		});
		
		JLabel lblNewLabel_7 = new JLabel("下面不选默认生成所有类型的文件:");
		lblNewLabel_7.setBounds(121, 397, 227, 15);
		contentPane.add(lblNewLabel_7);

	}
	//校验配置文件
	protected boolean checkConfig(HashMap<String, String> configHash) {
		return configHash==null?false:configHash.entrySet().stream().count()>0?true:false;
	}

	private void outInfoMessage(boolean flag,String message) {
		if(flag) {
			JOptionPane.showMessageDialog(configJpanel, "成功", "提示",JOptionPane.WARNING_MESSAGE);  
		}else {
			JOptionPane.showMessageDialog(configJpanel, "失败!"+message, "提示",JOptionPane.WARNING_MESSAGE);  
		}
	}
	
	//初始化配置窗口
	private void initConfigPanel() {
		//数据源地址
		String dataSourceUrl=configHash.get("DataSourceUrl");
		String userName=configHash.get("UserName");
		String password=configHash.get("Password");
		String projectUrl=configHash.get("ProjectUrl");
		String programName=configHash.get("ProgramName");

		JPanel configJp = new JPanel();
		configJp.setBorder(new EmptyBorder(5, 5, 5, 5));
		
		JLabel lblNewLabel = new JLabel("数据库源地址:");
		lblNewLabel.setBounds(87, 52, 104, 15);
		configJp.add(lblNewLabel);
		
		JTextArea textArea = new JTextArea();
		textArea.setLineWrap(true);
		textArea.setRows(8);
		textArea.setColumns(10);
		textArea.setText(dataSourceUrl);
		textArea.setBounds(201, 52, 357, 49);
		configJp.add(textArea);
		
		JLabel lblNewLabel_1 = new JLabel("用户名:");
		lblNewLabel_1.setBounds(87, 125, 69, 15);
		configJp.add(lblNewLabel_1);
		
		JTextField textField = new JTextField();
		textField.setBounds(201, 122, 143, 21);
		textField.setText(userName);
		configJp.add(textField);
		textField.setColumns(10);
		
		JLabel lblNewLabel_2 = new JLabel("密码:");
		lblNewLabel_2.setBounds(87, 165, 54, 15);
		configJp.add(lblNewLabel_2);
		
		JTextField textField_1 = new JTextField();
		textField_1.setBounds(201, 162, 143, 21);
		textField_1.setText(password);
		configJp.add(textField_1);
		textField_1.setColumns(10);
		
		JLabel lblNewLabelProject = new JLabel("项目地址:");
		lblNewLabelProject.setBounds(87, 205, 93, 15);
		configJp.add(lblNewLabelProject);
		
		JTextField textFieldProject = new JTextField();
		textFieldProject.setBounds(201, 202, 250, 21);
		textFieldProject.setText(projectUrl);
		configJp.add(textFieldProject);
		textFieldProject.setColumns(10);
		
		JLabel lblNewLabel_4 = new JLabel("开发人员名称:");
		lblNewLabel_4.setBounds(87, 245, 103, 15);
		configJp.add(lblNewLabel_4);
		
		JTextField textField_2 = new JTextField();
		textField_2.setBounds(201, 242, 160, 21);
		configJp.add(textField_2);
		textField_2.setText(programName);
		textField_2.setColumns(10);
		
		JButton btnNewButton = new JButton("提交");
		btnNewButton.setBounds(165, 273, 93, 23);
		configJp.add(btnNewButton);
		btnNewButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String dataSourceUrl=textArea.getText();
				String userName=textField.getText();
				String password=textField_1.getText();
				String projectUrl=textFieldProject.getText();
				String programName=textField_2.getText();
				if(dataSourceUrl.trim().isEmpty()
						||dataSourceUrl.trim().isEmpty()||dataSourceUrl.trim().isEmpty()
						||dataSourceUrl.trim().isEmpty()||programName.trim().isEmpty()) {
					JOptionPane.showMessageDialog(configJpanel, "失败！参数不允许为空", "提示",JOptionPane.WARNING_MESSAGE);  
                    return;
				}
				//修改配置文件并且重新加载配置
				updateConfigAndInitCofing(dataSourceUrl,userName,password,projectUrl,programName);
				//提示成功
				JOptionPane.showMessageDialog(configJpanel, "成功", "提示",JOptionPane.WARNING_MESSAGE);  
				//切换面板
				switchPanel(jPanelContent);
				
			}
		});
		
		JButton btnNewButton_1 = new JButton("取消");
		btnNewButton_1.setBounds(362, 273, 93, 23);
		configJp.add(btnNewButton_1);
		btnNewButton_1.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				switchPanel(jPanelContent);
			}
		});
		configJpanel=configJp;
		configJp.setLayout(null);

//		contentPanel.add(configJp, BorderLayout.CENTER);//中间面板

	}
	
	//修改配置文件并且重新加载配置
	protected void updateConfigAndInitCofing(String dataSourceUrl, String userName, String password, String projectUrl, String programName) {
		//修改配置文件
		updateConfigFile(dataSourceUrl,userName,password,projectUrl,programName);
		//更新配置信息
		initConfigInfo();
	}
	
	//修改配置文件
	private void updateConfigFile(String dataSourceUrl, String userName, String password, String projectUrl, String programName) {
		Properties prop = new PropertiesUtil();     
        try{
        	String path=new File("").getAbsolutePath();
//    		String fileUrl=path+"\\src\\"+"config.properties";
    		String fileUrl=path+"\\"+"config.properties";
    		File fileConfig=new File(fileUrl);
	        FileInputStream inputFile = new FileInputStream(fileConfig);
	        prop.load(inputFile);
            FileOutputStream oFile = new FileOutputStream(fileConfig);
            prop.setProperty("DataSourceUrl", dataSourceUrl);
            prop.setProperty("UserName", userName);
            prop.setProperty("Password", password);
            prop.setProperty("ProjectUrl", projectUrl);
            prop.setProperty("ProgramName", programName);
            prop.setProperty("CoreUrl", "\\src\\ptt\\core\\");
            prop.setProperty("BeanUrl", "\\src\\ptt\\bean\\");
            prop.setProperty("HandlerUrl", "\\src\\ptt\\handler\\");
            prop.setProperty("FrontEndUrl", "\\defaultroot\\");
            prop.store(oFile,"");
            oFile.flush();
            oFile.close();
        }
        catch(Exception e){
            System.out.println(e);
        }
	}

	//初始化配置信息
	private static void initConfigInfo() {
		Properties prop = new PropertiesUtil();  
		String path=new File("").getAbsolutePath();
//		String fileUrl=path+"\\src\\"+"config.properties";
		String fileUrl=path+"\\"+"config.properties";
        File fileConfig=new File(fileUrl);
        FileInputStream inputFile;
		try {
			inputFile = new FileInputStream(fileConfig);
	        prop.load(inputFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		prop.forEach((k,v)->{
			configHash.put((String)k,(String)v);
		});
	}
	
	//初始化readme信息
	private static void initReadMeInfo() {
		readMe=readFile("readme.txt");
	}
	
	//读取文件
	public static String readFile(String fileUrl){
		String result=null;
		StringBuilder resultSB=new StringBuilder();
		InputStream input=null;
		BufferedReader br=null;
		try {
			 //当前项目下路径
	        File file = new File("");
	        String filePath = file.getCanonicalPath();
//	        String fileUrlReal=filePath+"\\src\\"+fileUrl;
	        String fileUrlReal=filePath+"\\"+fileUrl;
			input=new FileInputStream(new File(fileUrlReal));
			br=new BufferedReader(new InputStreamReader(input));
			while((result=br.readLine())!=null) {
				resultSB.append(result);
				resultSB.append("\r\n");
			}
		}catch(IOException e) {
			e.printStackTrace();
		}finally {
				try {
					if(input!=null)
					input.close();
					if(br!=null)
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return resultSB.toString();
	}
}
//                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            